﻿//  --------------------------------
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/oxite/license
//  ---------------------------------
using System.Web.Mvc;
using Oxite.Extensions;
using Oxite.Infrastructure;
using Oxite.Models;
using ECube.SEC.FormsAuthentication.Extensions;
using ECube.SEC.FormsAuthentication.Models;
using ECube.SEC.FormsAuthentication.Services;
using ECube.SEC.Membership.Models;
using ECube.SEC.Membership.Services;
using Oxite.Services;
using Oxite.ViewModels;

namespace ECube.SEC.FormsAuthentication.Controllers
{
    public class UserController : Controller
    {
        private readonly IFormsAuthentication formsAuthentication;
        private readonly IUserService userService;
        private readonly IFormsAuthenticationUserService faUserService;

        public UserController(IFormsAuthentication formsAuthentication, IUserService userService, IFormsAuthenticationUserService faUserService)
        {
            this.formsAuthentication = formsAuthentication;
            this.userService = userService;
            this.faUserService = faUserService;
        }

        public ActionResult SignIn()
        {
            return this.View();
        }

        [HttpPost]
        public object SignIn(UserLogin login, string returnUrl)
        {
            
                if (ModelState.IsValid)
                {
                    if (userService.SignIn(() => userService.GetUser(login.UserName,login.Password,login.LoginDomain), 
                        (u) => formsAuthentication.SetAuthCookie(u.Name, login.RememberMe)))
                    {
                        if (!string.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith("/"))
                            return Redirect(returnUrl);

                        return Redirect(Url.AppPath(Url.Home()));
                    }

                    ModelState.AddModelError("_FORM", "输入的用户名或密码不正确！");
                }
           
            return SignIn();
        }

        public ActionResult SignOut()
        {
            formsAuthentication.SignOut();

            userService.SignOut();

            return Redirect(Url.AppPath(Url.Home()));
        }

        public UserRegister Register()
        {
            return new UserRegister();
        }
        [HttpPost]
        public UserRegister Register(UserRegister user,string domain)
        {
            if (ModelState.IsValid)
            {
                UserInputAdd input = new UserInputAdd(user.UserName, user.DisplayName, user.Email, user.Password, user.ConfirmPassword);
                ModelResult<User> result =  userService.AddUser(input);
                if (result.IsValid)
                {
                    this.ViewData["ModelResult"] = true;
                    //HACK: (erikpo) This should be moved out into some event saying "ok, i'm done adding the user, module, do you want to do something else too?" (maybe in the AddUser service call instead)
                    string passwordSalt = System.Guid.NewGuid().ToString("N");
                    string password = input.Password.SaltAndHash(passwordSalt);
                    userService.SetModuleData(result.Item, "FormsAuthentication", string.Format("{0}|{1}", passwordSalt, password));

                }
                else
                {
                    ModelState.AddModelErrors(result.ValidationState);
                }
            }
            return (user);
        }

        [HttpGet]
        public User ChangePassword(User user)
        {
            if (user == null) return null;

            //TODO: (erikpo) Check permissions or let the current user change their password

            return user;
        }

        [HttpPost]
        public object ChangePassword(User user, UserChangePasswordInput userInput)
        {
            if (user == null) return null;

            //TODO: (erikpo) Check permissions

            if (ModelState.IsValid)
            {
                ModelResult results = faUserService.ChangePassword(user, userInput);

                if (!results.IsValid)
                {
                    ModelState.AddModelErrors(results.ValidationState);

                    return ChangePassword(user);
                }
            
                return Redirect(Url.AppPath(Url.ManageUsers()));
            }
            return user;
        }
    }
}
